#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 100

struct tcp_data
{
    short command = 0;
    char data[40] = "holle server.";
};

int main(){
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(55550);

    if(0 > connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr))){
        perror("connect error");
        return -1;
    }

    char buff[BUFSIZE];
    tcp_data data;
    data.command = 1;
    strcpy(data.data, "holle server.");
    while(true){
        memcpy(buff, &data, sizeof(data));
        if(0 > write(sock, buff, sizeof(data))){
            perror("write failed 1");
            continue;
        }else{
            if(0 > read(sock, buff, sizeof(data))){
                perror("read failed !");
                continue;
            }else{
                memcpy(&data, buff, sizeof(data));
                std::cout << "feed back from server :" << std::endl;
                std::cout << "command : " << data.command << std::endl;
                std::cout << "data : " << data.data << std::endl << std::endl;
                if(0 == data.command){
                    break;
                }
            }
            data.command ++;
            data.command %= 100;
        }
    }
    close(sock);
    return 0;
}
